package cn.yunbamboos.mybatis.toolkit;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.TypeUtil;
import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.yunbamboos.mybatis.metadata.TableInfoHelper;
import cn.yunbamboos.mybatis.metadata.TablePrimaryKeyInfo;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;

public class GenericUtils {

    /**
     * 获取指定类的泛型类型
     */
    public static Class<?> getTypeArgument(Class<?> clz) {
        Type type = TypeUtil.getTypeArgument(clz, 0);
        Assert.notNull(type, "{} get type is null", clz.getName());
        Class<?> modelClass = TypeUtil.getClass(type);
        Assert.notNull(modelClass, "{} get type is null", clz.getName());
        return modelClass;
    }

    public static Optional<Conditions> createConditions(Class<?> clz, Serializable... ids) {
        Class<?> modelClass = GenericUtils.getTypeArgument(clz);
        return TableInfoHelper.getTableInfo(modelClass).map(tableInfo -> {
            List<TablePrimaryKeyInfo> pks = tableInfo.getPrimaryKeyList();
            Assert.isTrue(pks.size() == ids.length, "{}.{} set pk size parmas num is error", clz.getName(), "deleteByPrimaryKeys");
            Conditions conditions = new Conditions();
            for (int i = 0; i < pks.size(); i++) {
                TablePrimaryKeyInfo pk = pks.get(i);
                Serializable value = ids[i];
                conditions.add(pk.getColumn(), value);
            }
            return conditions;
        });
    }


}
